package com.yuanqi.controller;

import com.yuanqi.domain.User;
import com.yuanqi.service.UserService;
import com.yuanqi.service.FileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/system/user")
@CrossOrigin(origins = "*")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private FileUploadService fileUploadService;
    
    /**
     * 获取用户个人信息
     */
    @GetMapping("/profile/{userId}")
    public ResponseEntity<?> getUserProfile(@PathVariable Long userId) {
        try {
            User user = userService.getUserById(userId);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 返回安全的用户信息（不包含密码等敏感信息）
            Map<String, Object> profile = new HashMap<>();
            profile.put("id", user.getId());
            profile.put("username", user.getUsername());
            profile.put("name", user.getName());
            profile.put("email", user.getEmail());
            profile.put("mobile", user.getMobile());
            profile.put("avatarUrl", user.getAvatarUrl());
            profile.put("bio", user.getBio());
            profile.put("department", user.getDepartment());
            profile.put("position", user.getPosition());
            profile.put("status", user.getStatus());
            profile.put("isSuperAdmin", user.getIsSuperAdmin());
            profile.put("lastLoginAt", user.getLastLoginAt());
            profile.put("createdAt", user.getCreatedAt());
            profile.put("updatedAt", user.getUpdatedAt());
            
            return ResponseEntity.ok(profile);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 更新用户个人信息
     */
    @PutMapping("/profile/{userId}")
    public ResponseEntity<?> updateUserProfile(@PathVariable Long userId, @RequestBody Map<String, Object> profileData) {
        try {
            User updatedUser = userService.updateUserProfile(userId, profileData);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "个人信息更新成功");
            response.put("user", updatedUser);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "更新个人信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 通过用户名获取用户个人信息（用于前端仅有username场景）
     */
    @GetMapping("/profile/by-username")
    public ResponseEntity<?> getUserProfileByUsername(@RequestParam String username) {
        try {
            User user = userService.getUserByUsername(username);
            if (user == null) {
                return ResponseEntity.notFound().build();
            }

            Map<String, Object> profile = new HashMap<>();
            profile.put("id", user.getId());
            profile.put("username", user.getUsername());
            profile.put("name", user.getName());
            profile.put("email", user.getEmail());
            profile.put("mobile", user.getMobile());
            profile.put("avatarUrl", user.getAvatarUrl());
            profile.put("bio", user.getBio());
            profile.put("department", user.getDepartment());
            profile.put("position", user.getPosition());
            profile.put("status", user.getStatus());
            profile.put("isSuperAdmin", user.getIsSuperAdmin());
            profile.put("lastLoginAt", user.getLastLoginAt());
            profile.put("createdAt", user.getCreatedAt());
            profile.put("updatedAt", user.getUpdatedAt());

            return ResponseEntity.ok(profile);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "通过用户名获取用户信息失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    /**
     * 修改用户密码
     */
    @PutMapping("/password/{userId}")
    public ResponseEntity<?> changePassword(@PathVariable Long userId, @RequestBody Map<String, String> passwordData) {
        try {
            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");
            
            if (oldPassword == null || newPassword == null) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "旧密码和新密码不能为空");
                return ResponseEntity.badRequest().body(error);
            }
            
            boolean success = userService.changePassword(userId, oldPassword, newPassword);
            
            if (success) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "密码修改成功");
                return ResponseEntity.ok(response);
            } else {
                Map<String, String> error = new HashMap<>();
                error.put("error", "密码修改失败");
                return ResponseEntity.badRequest().body(error);
            }
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "密码修改失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 更新用户头像
     */
    @PutMapping("/avatar/{userId}")
    public ResponseEntity<?> updateAvatar(@PathVariable Long userId, @RequestBody Map<String, String> avatarData) {
        try {
            String avatarUrl = avatarData.get("avatarUrl");
            
            if (avatarUrl == null || avatarUrl.trim().isEmpty()) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "头像URL不能为空");
                return ResponseEntity.badRequest().body(error);
            }
            
            User updatedUser = userService.updateAvatar(userId, avatarUrl);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "头像更新成功");
            response.put("avatarUrl", updatedUser.getAvatarUrl());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "头像更新失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username")
    public ResponseEntity<?> checkUsernameAvailability(@RequestParam String username, @RequestParam(required = false) Long excludeUserId) {
        try {
            boolean available = userService.isUsernameAvailable(username, excludeUserId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("username", username);
            response.put("available", available);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "检查用户名失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 检查邮箱是否可用
     */
    @GetMapping("/check-email")
    public ResponseEntity<?> checkEmailAvailability(@RequestParam String email, @RequestParam(required = false) Long excludeUserId) {
        try {
            boolean available = userService.isEmailAvailable(email, excludeUserId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("email", email);
            response.put("available", available);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "检查邮箱失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 检查手机号是否可用
     */
    @GetMapping("/check-mobile")
    public ResponseEntity<?> checkMobileAvailability(@RequestParam String mobile, @RequestParam(required = false) Long excludeUserId) {
        try {
            boolean available = userService.isMobileAvailable(mobile, excludeUserId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("mobile", mobile);
            response.put("available", available);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "检查手机号失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
    
    /**
     * 上传头像文件
     */
    @PostMapping("/upload-avatar/{userId}")
    public ResponseEntity<?> uploadAvatar(@PathVariable Long userId, @RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "请选择要上传的文件");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "只支持图片文件");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 验证文件大小 (5MB)
            if (file.getSize() > 5 * 1024 * 1024) {
                Map<String, String> error = new HashMap<>();
                error.put("error", "文件大小不能超过5MB");
                return ResponseEntity.badRequest().body(error);
            }
            
            // 上传文件到MinIO
            String fileName = fileUploadService.uploadAvatar(file, userId);
            String fileUrl = fileUploadService.getFileUrl(fileName);
            
            // 更新用户头像URL
            User updatedUser = userService.updateAvatar(userId, fileUrl);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "头像上传成功");
            response.put("fileName", fileName);
            response.put("fileUrl", fileUrl);
            response.put("user", updatedUser);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> error = new HashMap<>();
            error.put("error", "头像上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }
}
